<!--
 * @description 标签分类
 * @author dumeng
 * @date 2022/1/5
 -->
<template>
  <div class="label-category-page">
    <div class="classify-btn">
      <div class="btn-title">
        <span>标签分类</span>
      </div>
      <div class="btn-btns">
        <el-button
          v-if="!allListIsEdit"
          @click="handleAddClassify"
        >添加分类</el-button>
      </div>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      style="width: 100%; margin-bottom: 20px"
      row-key="id"
      default-expand-all
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      size="mini"
      :indent="30"
    >
      <el-table-column label="分类名称">
        <template slot-scope="scope">
          <template v-if="scope.row.isEdit">
            <el-input
              v-model="scope.row.name"
              class="edit-input"
              :class="[scope.row.parentId != -1 && 'children']"
              size="small"
              :maxlength="15"
            />
            <el-button
              v-if="!allListIsEdit"
              class="addchild-btn"
              size="small"
              type="text"
              @click="addchild(scope.row)"
            >添加子分类</el-button>
          </template>
          <template v-else>
            <span :class="[scope.row.parentId != -1 && 'children']">{{
              scope.row.name
            }}</span>
            <el-button
              v-if="!allListIsEdit"
              class="addchild-btn"
              size="small"
              type="text"
              @click="addchild(scope.row)"
            >添加子分类</el-button>
          </template>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="200">

        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="ZT01"
            inactive-value="ZT02"
            @change="changeStatus(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="移动" align="center" width="200">
        <template slot-scope="scope">
          <el-button
            :disabled="scope.row.isFirst"
            type="text"
            @click="move(scope.row, 'SY')"
          >上移</el-button>
          <el-button
            :disabled="scope.row.isLast"
            type="text"
            @click="move(scope.row, 'XY')"
          >下移</el-button>
        </template>
      </el-table-column>
      <el-table-column label="标签数量" prop="labelCount" align="center" width="200" />
      <el-table-column label="操作" align="center" width="300">
        <template slot-scope="scope">
          <template v-if="scope.row.isEdit">
            <el-button
              type="text"
              style="color: #18a5fd; font-size: 14px"
              @click="handleSave(scope.row)"
            >保存</el-button>
            <el-button
              type="text"
              style="color: #18a5fd; font-size: 14px"
              @click="handleCancel(scope.row)"
            >取消</el-button>
          </template>
          <template v-else>
            <el-button
              type="text"
              style="color: #18a5fd; font-size: 14px"
              @click="handleUpdate(scope.row)"
            >编辑</el-button>
          </template>
          <el-button
            type="text"
            style="color: #18a5fd; font-size: 14px"
            @click="handleDel(scope.row)"
          >删除</el-button>
          <el-button
            type="text"
            style="color: #18a5fd; font-size: 14px"
            @click="handleAddLabel(scope.row)"
          >添加标签</el-button>
          <el-button
            type="text"
            style="color: #18a5fd; font-size: 14px"
            @click="viewLabel(scope.row)"
          >查看标签</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 新增&编辑 -->
    <el-dialog
      v-el-drag-dialog
      title="标签"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      center
      custom-class="my-dialog"
      width="800px"
      :fullscreen="true"
      :destroy-on-close="true"
      @close="handleFormCancel"
    >
      <div class="content">
        <split-pane v-if="!isView" split="vertical" :min-percent="0" :default-percent="30">
          <template slot="paneL">
            <p>已选择标签：</p>
            <ul class="select-user">
              <li v-for="(item, index) in selection" :key="index">{{ item.name }}</li>
            </ul>
          </template>
          <template slot="paneR">
            <label-list :key="time" :is-component="true" :is-show="true" @checked="handleChecked" />
          </template>
        </split-pane>
        <label-list v-if="isView" :key="time" :classify-id="classifyId" :is-component="true" />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button style="padding: 8px 30px;" @click="dialogFormVisible = false">取消</el-button>
        <el-button
          v-if="!isView"
          style="padding: 8px 30px;"
          type="primary"
          @click="handleSubim"
        >确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import elDragDialog from '@/directive/el-drag-dialog'
import { queryPage, del, updateStatus, update, insert, move, addlabels } from '../api'
import splitPane from 'vue-splitpane'
import LabelList from '../../labellist/pages/index'
export default {
  name: 'LabelCategory',
  directives: { elDragDialog },
  components: { splitPane, LabelList },
  filters: {
    formatStatus(val) {
      return val === 0 ? '启用' : val === 1 ? '禁用' : '禁用'
    },
    formatIshot(val) {
      return val === 0 ? '是' : val === 1 ? '否' : '否'
    }
  },
  data() {
    return {
      pageLoading: true,
      activeTab: '',
      listLoading: false,
      searchshow: true,
      expandAll: true,
      list: [],
      curEditRow: {},
      allListIsEdit: false, // 分类树是否存在编辑情况，如果存在隐藏所有的添加下级按钮
      sortable: null,
      dict: {
        XWFL: [], // 分类
        ZT: []
      },
      treeLevel: '',
      dialogFormVisible: false,
      selection: [],
      isView: false,
      classifyId: '',
      time: new Date().getTime()
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /**
     * 添加标签
     */
    handleAddLabel(row) {
      this.isView = false
      this.classifyId = row.id
      this.time = new Date().getTime()
      this.dialogFormVisible = true
    },
    /**
     * 分类移动
     */
    move(row, dir) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      return new Promise((resolve, reject) => {
        move({ id: row.id, msg: dir }).then(() => {
          this.$message({
            message: '处理成功',
            type: 'success',
            duration: 2000
          })
          loading.close()
          this.getList()
        }).catch(error => {
          loading.close()
          this.getList()
          reject(error)
        })
      })
    },
    /**
     * 切换启用禁用状态
     */
    changeStatus(row) {
      if (!row.id) {
        return
      }
      if (!row.isEdit) {
        const loading = this.$loading({
          lock: true,
          text: '请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        return new Promise((resolve, reject) => {
          updateStatus({ id: row.id, status: row.status }).then(() => {
            this.$message({
              message: '处理成功',
              type: 'success',
              duration: 2000
            })
            loading.close()
            this.getList()
          }).catch(error => {
            loading.close()
            this.getList()
            reject(error)
          })
        })
      }
    },
    // 取消
    handleCancel(row) {
      if (row.id) {
        row['classifyName'] = this.curEditRow.classifyName
        row['status'] = this.curEditRow.status
        this.findPathByLeafId(row.id, this.list).isEdit = false
      } else {
        if (row.parentId) {
          this.findPathByLeafId(row.parentId, this.list).children.shift()
        } else {
          this.list.shift()
        }
      }
      this.allListIsEdit = false
    },
    handleUpdate(row) {
      if (this.allListIsEdit) {
        this.$message({
          message: '请先保存新添加分类',
          type: 'warning'
        })
        return
      } else {
        this.allListIsEdit = true
        this.curEditRow = Object.assign({}, row)
        this.findPathByLeafId(row.id, this.list).isEdit = true
      }
    },
    handleSave(row) {
      var obj = {
        id: row.id,
        name: row.name,
        status: row.status,
        parentId: row.parentId,
        type: 'FLLX_XXBQ'
      }
      this.save(obj)
    },
    save(obj) {
      if (!obj.name) {
        this.$message({
          message: '请填写分类名称',
          type: 'warning'
        })
        return
      }
      const pattern = new RegExp("^\\s|[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？]|\\s$")
      if (pattern.test(obj.name)) {
        this.$message({
          message: '请勿输入特殊字符或前后空格',
          type: 'warning'
        })
        return
      }
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      if (obj.id) {
        return new Promise((resolve, reject) => {
          update(obj).then(() => {
            this.allListIsEdit = false
            this.$message({
              message: '处理成功',
              type: 'success',
              duration: 2000
            })
            loading.close()
            this.getList()
          }).catch(error => {
            loading.close()
            reject(error)
          })
        })
      } else {
        return new Promise((resolve, reject) => {
          insert(obj).then(() => {
            this.allListIsEdit = false
            this.$message({
              message: '处理成功',
              type: 'success',
              duration: 2000
            })
            loading.close()

            this.getList()
          }).catch(error => {
            loading.close()
            reject(error)
          })
        })
      }
    },
    handleDel(row) {
      if (row.id) {
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.del(row.id)
        }).catch(() => {
        })
      } else {
        if (row.parentId) {
          this.findPathByLeafId(row.parentId, this.list).children.shift()
        } else {
          this.list.shift()
        }
        this.allListIsEdit = false
      }
    },
    del(id) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      return new Promise((resolve, reject) => {
        del({ id: id }).then(() => {
          loading.close()
          this.$message({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    },
    getList() {
      this.allListIsEdit = false
      this.listLoading = true
      return new Promise((resolve, reject) => {
        queryPage({ type: 'FLLX_XXBQ' }).then(response => {
          this.listLoading = false
          this.list = this.initData(response.data.data)
          this.pageLoading = false
        }).catch(error => {
          this.listLoading = false
          this.pageLoading = false
          reject(error)
        })
      })
    },
    /**
     * 递归增加是否可以上移下移标识
     * @param data
     * @returns {*}
     */
    initData(data, level = 1) {
      data.forEach((item, index) => {
        item['isFirst'] = false
        item['isLast'] = false
        item['isEdit'] = false
        if (index === 0) {
          item['isFirst'] = true
        }
        if (index === data.length - 1) {
          item['isLast'] = true
        }
        item['level'] = level
        if (item.children && item.children.length > 0) {
          return this.initData(item.children, level + 1)
        }
      })
      return data
    },
    addchild(row) {
      this.allListIsEdit = true
      row['_expanded'] = true
      /* let length = ''
      if (row.children) {
        length = row.children.length
      } else {

      }*/
      const obj = {
        id: '',
        classifyName: '',
        status: 'ZT01',
        isFirst: true,
        isLast: true,
        isEdit: true,
        parentId: row.id
      }
      this.findPathByLeafId(row.id, this.list).children.unshift(obj)
    },
    /**
     * 根据id递归查找所在的对象
     * @param data
     * @returns {*}
     */
    findPathByLeafId(leafId, nodes, path) {
      if (path === undefined) {
        path = {}
      }
      for (var i = 0; i < nodes.length; i++) {
        var tmpPath = path
        if (leafId === nodes[i].id) {
          tmpPath = nodes[i]
          return tmpPath
        }
        if (nodes[i].children) {
          var findResult = this.findPathByLeafId(leafId, nodes[i].children, tmpPath)
          if (findResult) {
            return findResult
          }
        }
      }
    },
    handleAddClassify() {
      this.allListIsEdit = true
      const list = this.list
      var length = list.length
      const obj = {
        id: '',
        parentId: '',
        classifyName: '',
        status: 'ZT01',
        isEdit: true,
        isFirst: true,
        isLast: true,
        index: length
      }
      list.unshift(obj)
      this.$set(this, 'list', list)
    },
    handleChecked(checked) {
      this.selection = checked
    },
    handleSubim() {
      if (this.isView) {
        return
      }
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const labelId = this.selection.map(item => item.id).join(',')
      addlabels({ labelId, classifyId: this.classifyId }).then(res => {
        loading.close()
        this.$message({
          message: '操作成功',
          type: 'success'
        })
        this.getList()
        this.dialogFormVisible = false
      }).catch(
        () => {
          loading.close()
        }
      )
    },
    viewLabel(row) {
      this.isView = true
      this.classifyId = row.id
      this.time = new Date().getTime()
      this.dialogFormVisible = true
    },
    handleFormCancel() {
      this.selection = []
      this.dialogFormVisible = false
      this.getList()
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
$dark_gray: #bfced6;
@import "@/styles/mixin.scss";
.label-category-page {
  padding: 20px;
  height: 100%;
  .el-dialog__footer{
    padding:20px 0 0 0 !important;
  }
.my-dialog{
  .el-dialog__body{
    height: calc(100vh - 150px);
    overflow: hidden;
  }
  .el-dialog__footer{
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
  .content{
    overflow: auto;
    height: 87vh;
    padding-bottom: 30px;
  }
  .classify-btn {
    display: flex;
    height: 46px;
    line-height: 46px;
    .btn-title {
      flex: 1;
      font-size: 16px;
      font-weight: bold;
      color: rgba(51, 51, 51, 1);
      padding: 0 10px;
    }
  }
  .el-table {
    background-color: transparent;
    .cell {
      display: flex;
      align-items: center;
      text-align: left;
    }
    thead {
      th {
        font-size: 14px;
        font-family: PingFangSC-Regular;
        font-weight: 400;
        color: rgba(166, 166, 166, 1);
      }
    }
    th,
    tr {
      background-color: transparent;
    }
    tbody {
      background-color: #ffffff;
      font-weight: 500;
    }
  }
  .select-user {
    padding: 0;
    margin: 0;
    height: calc(100vh - 185px);
    overflow: auto;
    list-style: none;

    li {
      padding: 5px 8px;
      margin: 0;
      float: left;
      list-style: none;
      font-size: 14px;
      @include font-color($mainColor);
      @include border-color(1px, solid, $mainColor);
      border-radius: 5px;
      margin-left: 8px;
      margin-bottom: 8px;
    }
  }
}
</style>
<style scoped lang="scss">
.drag-handler {
  width: 20px;
  height: 20px;
  cursor: pointer;
  vertical-align: middle;
}

.edit-input {
  padding-right: 80px;
  &.children {
    padding-left: 20px;
  }
}

.addchild-btn {
  position: absolute;
  right: 15px;
  top: 6px;
}

</style>
